package com.sky.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * @ClassName RedisConfiguration
 * @Description Redis配置类
 * @Author sld
 * @Date 2024/7/10 8:52
 * Version 1.0
 **/
@Configuration
@Slf4j
public class RedisConfiguration {
    // 创建序列化器
    FastJsonRedisSerializer<Object> serializer =
            new FastJsonRedisSerializer<>(Object.class);
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("开始创建RedisTemplate对象...");
        // 创建RedisTemplate对象
        RedisTemplate redisTemplate = new RedisTemplate();
        // 设置RedisConnectionFactory，必须加
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置key的序列化器
        redisTemplate.setKeySerializer(serializer);
        // 设置value的序列化器
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    // @Bean
    // public CacheManager cacheManager(RedisConnectionFactory factory) {
    //     // 配置序列化（解决乱码的问题）
    //     RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    //             // 默认 30天过期
    //             .entryTtl(Duration.ofDays(30))
    //                 // 设置key的序列化方式
    //             // .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
    //                 // 设置value的序列化方式
    //             .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
    //             .disableCachingNullValues();
    //     RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
    //             .cacheDefaults(config)
    //             .build();
    //     return cacheManager;
    // }
}
